<template>
  <div class="custom-title-bar" @dblclick="onTitleBarDblClick">
    <!-- 左侧：应用图标和标题 -->
    <div class="title-bar-left">
      <div class="app-icon">
        <svg-icon icon-class="hospital" />
      </div>
      <div class="app-title">{{ sysTitle }}</div>
    </div>

    <!-- 中间：TopNav导航菜单 -->
    <div class="title-bar-nav">
      <TopNav />
    </div>

    <!-- 右侧：用户信息和窗口控制按钮 -->
    <div class="title-bar-right">
      <!-- 窗口控制按钮：仅在 Electron 环境显示 -->
      <div class="window-controls" v-if="isElectronEnv">
        <!-- 刷新按钮：统一使用 control-btn 风格，保持与其他按钮一致 -->
        <button class="control-btn refresh-btn" title="刷新" @click="onRefresh">
          <svg class="icon" viewBox="0 0 1024 1024" width="128" height="128">
            <path
              d="M949.948959 146.249899l0 255.82655c0 21.980617-13.988596 35.969213-35.969213 35.969213l-255.82655 0c-13.988596 0-25.982768-7.992021-33.972742-21.980617-5.997598-13.988596-4.001127-27.977191 7.990998-39.97034l79.941704-77.945233c-55.954383-51.973722-121.917724-77.955466-199.862957-77.955466-37.974893 0-75.949786 8.002254-113.924679 21.99085-37.974893 15.984043-67.947532 37.974893-91.933829 63.956637-25.981744 23.986297-47.972595 53.958936-63.956637 91.933829-29.982872 73.954339-29.982872 153.895019 0 227.849358 15.984043 37.975916 37.974893 67.947532 63.956637 91.933829 23.986297 25.982768 53.958936 47.973618 91.933829 63.956637 37.974893 13.988596 75.949786 21.99085 113.924679 21.99085 45.966914 0 87.941911-9.997702 127.913275-29.981848 41.97602-17.989723 75.950809-45.966914 101.930507-83.942831 7.993045-4.001127 11.994172-5.995551 13.988596-5.995551 5.997598 0 9.998725 1.994424 13.988596 5.995551l77.957513 77.945233c3.988848 4.001127 5.986341 7.993045 5.986341 11.994172 0 1.994424-1.99647 5.995551-3.990894 11.994172-43.972491 51.962465-93.940532 91.933829-151.898549 117.91455-53.958936 25.982768-115.921149 39.971363-185.874361 39.971363-61.96119 0-119.921253-11.983939-169.889295-33.972742C284.40084 889.74325 236.438479 857.764931 202.464713 821.785485c-35.979446-33.972742-67.957765-81.936127-93.939509-139.897214-45.966914-101.930507-45.966914-237.846036 0-339.777567 25.981744-57.960063 57.960063-105.922425 93.939509-139.89619 33.973766-35.979446 81.936127-67.957765 139.89619-93.939509 49.968042-21.99085 107.928105-33.973766 169.889295-33.973766 55.963593 0 109.923552 9.987468 161.886017 29.972639 53.969169 21.99085 101.932554 51.963489 139.907447 89.938382l73.954339-73.944106c9.987468-9.997702 23.987321-13.988596 39.971363-8.002254C941.956937 120.268154 949.948959 132.261303 949.948959 146.249899z"
              fill="currentColor"
            />
          </svg>
        </button>
        <button class="control-btn minimize-btn" title="最小化" @click="minimizeWindow">
          <!-- 现代化扁平化最小化图标 -->
          <svg class="icon" viewBox="0 0 24 24" aria-hidden="true" shape-rendering="geometricPrecision">
            <!-- 水平细线：使用非缩放描边，确保不同DPI清晰 -->
            <path
              d="M5 12h14"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              vector-effect="non-scaling-stroke"
            />
          </svg>
        </button>
        <button class="control-btn maximize-btn" :title="maximizeBtnTitle" @click="onToggleSize">
          <!-- 图标切换动画：200-300ms 平滑过渡 -->
          <transition name="icon-swap" mode="out-in">
            <!-- 正常大小：显示最大化图标（单个方框） -->
            <svg
              v-if="windowState === 'normal'"
              key="icon-maximize"
              class="icon"
              viewBox="0 0 24 24"
              aria-hidden="true"
              shape-rendering="geometricPrecision"
            >
              <rect
                x="4"
                y="4"
                width="16"
                height="16"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                rx="2"
                vector-effect="non-scaling-stroke"
              />
            </svg>

            <!-- 最大化：显示还原图标（两个重叠方框） -->
            <svg
              v-else-if="windowState === 'maximized'"
              key="icon-restore"
              class="icon"
              viewBox="0 0 24 24"
              aria-hidden="true"
              shape-rendering="geometricPrecision"
            >
              <rect
                x="4"
                y="9"
                width="12"
                height="12"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                rx="2"
                vector-effect="non-scaling-stroke"
              />
              <rect
                x="9"
                y="5"
                width="12"
                height="12"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                rx="2"
                vector-effect="non-scaling-stroke"
              />
            </svg>

            <!-- 最小化：显示恢复图标（窗口+向上箭头） -->
            <svg
              v-else
              key="icon-restore-from-min"
              class="icon"
              viewBox="0 0 24 24"
              aria-hidden="true"
              shape-rendering="geometricPrecision"
            >
              <rect
                x="6"
                y="9"
                width="12"
                height="9"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                rx="2"
                vector-effect="non-scaling-stroke"
              />
              <path
                d="M12 6l3 3M12 6l-3 3M12 6v6"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                vector-effect="non-scaling-stroke"
              />
            </svg>
          </transition>
        </button>
        <button class="control-btn close-btn" title="关闭" @click="closeWindow">
          <svg viewBox="0 0 12 12">
            <path d="M2 2 L10 10 M10 2 L2 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import TopNav from '@/components/TopNav'
// 引入空闲刷新销毁函数：点击刷新前先清理事件与计时器，避免残留影响
import { destroyIdleRefresh } from '@/utils/idleRefresh'
const sysTitle = import.meta.env.VITE_APP_TITLE
// 三态窗口状态：normal | maximized | minimized
const windowState = ref('normal')
// 中间按钮标题：与系统原生逻辑一致
const maximizeBtnTitle = computed(() =>
  windowState.value === 'maximized' ? '还原' : windowState.value === 'minimized' ? '恢复' : '最大化'
)

// 检测是否在 Electron 环境运行（多重兜底）
const detectElectronEnv = () => {
  try {
    // 1) 通过预加载暴露的 API 判断（优先）
    if (typeof window !== 'undefined' && window.electronAPI) return true
    // 2) 通过 UA 标识判断
    if (typeof navigator !== 'undefined' && navigator.userAgent?.includes('Electron')) return true
    // 3) 通过 process.versions.electron 判断（某些隔离关闭设置下可用）
    if (typeof process !== 'undefined' && process.versions?.electron) return true
  } catch {
    // 忽略错误并返回 false
  }
  return false
}
const isElectronEnv = ref(detectElectronEnv())

// 组件是否已卸载标记，避免卸载后继续更新状态
let isDestroyed = false

// 检测是否在iframe环境中运行
const isInIframe = () => {
  try {
    return window.self !== window.top
  } catch {
    return true
  }
}

// 窗口控制函数 - 根据环境选择通信方式
const minimizeWindow = () => {
  if (isInIframe()) {
    // 在iframe中，向父窗口发送最小化消息
    window.parent.postMessage(
      {
        type: 'window-control',
        data: { action: 'minimize' }
      },
      '*'
    )
  } else {
    // 直接运行时，调用Electron API
    if (window.electronAPI && window.electronAPI.minimizeWindow) {
      window.electronAPI.minimizeWindow()
    }
  }
}

// 中间按钮点击：根据当前状态最大化/还原或从最小化恢复
const onToggleSize = () => {
  if (isInIframe()) {
    const action = windowState.value === 'minimized' ? 'restore' : 'maximize'
    window.parent.postMessage({ type: 'window-control', data: { action } }, '*')
  } else {
    if (windowState.value === 'minimized' && window.electronAPI?.restoreWindow) {
      window.electronAPI.restoreWindow()
    } else if (window.electronAPI?.maximizeWindow) {
      window.electronAPI.maximizeWindow()
    }
  }
}

const closeWindow = () => {
  if (isInIframe()) {
    // 在iframe中，向父窗口发送关闭消息
    window.parent.postMessage(
      {
        type: 'window-control',
        data: { action: 'close' }
      },
      '*'
    )
  } else {
    // 直接运行时，调用Electron API
    if (window.electronAPI && window.electronAPI.closeWindow) {
      window.electronAPI.closeWindow()
    }
  }
}

// 标题栏双击：在非 iframe 环境下，调用 Electron API 实现最大化/还原
// 关键点：双击标题栏为操作系统的约定动作，这里主动模拟该行为
const onTitleBarDblClick = () => {
  if (isInIframe()) {
    // 在 iframe 中，交由父窗口处理最大化/还原
    const action = windowState.value === 'maximized' ? 'restore' : 'maximize'
    window.parent.postMessage({ type: 'window-control', data: { action } }, '*')
  } else {
    // 直接运行时，根据当前状态选择还原或最大化
    if (windowState.value === 'maximized' && window.electronAPI?.restoreWindow) {
      window.electronAPI.restoreWindow()
      windowState.value = 'normal'
    } else if (window.electronAPI?.maximizeWindow) {
      window.electronAPI.maximizeWindow()
      windowState.value = 'maximized'
    }
  }
}

// 刷新逻辑：
// 1）先销毁空闲刷新管理器，确保不再监听交互事件与定时器；
// 2）触发页面刷新；在 iframe 环境与直接运行环境均使用 location.reload，统一行为
const onRefresh = () => {
  try {
    // 关键点：销毁空闲刷新模块，防止已注册的倒计时或监听在刷新过程中干扰
    destroyIdleRefresh()
  } catch (e) {
    // 安全兜底：忽略异常以保证刷新不受影响
    console.warn('销毁空闲刷新失败:', e)
  }
  // 执行页面刷新（不使用已废弃的强制刷新参数）
  window.location.reload()
}

// 导航区域默认拖动：移除长按逻辑，改为通过 CSS 控制交互元素 no-drag

// 监听来自父窗口的消息（如窗口状态变化）
const handleParentMessage = event => {
  if (event.data.type === 'window-state-changed' || event.data.type === 'window-state-change') {
    const payload = event.data.data ?? event.data.state ?? event.data
    updateStateFromPayload(payload)
  }
}

// 监听Electron窗口状态变化
const handleWindowStateChange = payload => {
  if (!isDestroyed) updateStateFromPayload(payload)
}

// 统一处理不同负载结构，更新windowState
function updateStateFromPayload(payload) {
  if (isDestroyed) return
  if (typeof payload === 'boolean') {
    windowState.value = payload ? 'maximized' : 'normal'
    return
  }
  if (payload && typeof payload === 'object') {
    if (typeof payload.state === 'string') {
      windowState.value = payload.state
      return
    }
    if (payload.isMinimized) {
      windowState.value = 'minimized'
    } else if (payload.isMaximized) {
      windowState.value = 'maximized'
    } else {
      windowState.value = 'normal'
    }
  }
}

onMounted(() => {
  // 运行时再校正一次 Electron 环境（避免热重载场景）
  isElectronEnv.value = detectElectronEnv()
  if (isInIframe()) {
    // 在iframe中，监听来自父窗口的消息
    window.addEventListener('message', handleParentMessage)
  } else {
    // 直接运行时，监听Electron窗口状态变化
    if (window.electronAPI?.onWindowStateChange) {
      window.electronAPI.onWindowStateChange(handleWindowStateChange)
    }
    // 初始化窗口状态（同时查询是否最小化/最大化）
    const init = async () => {
      try {
        const isMin = await window.electronAPI?.isMinimized?.()
        const isMax = await window.electronAPI?.isMaximized?.()
        if (isMin) {
          windowState.value = 'minimized'
        } else if (isMax) {
          windowState.value = 'maximized'
        } else {
          windowState.value = 'normal'
        }
      } catch {
        windowState.value = 'normal'
      }
    }
    init()
  }
})

onUnmounted(() => {
  isDestroyed = true
  if (isInIframe()) {
    // 移除父窗口消息监听器
    window.removeEventListener('message', handleParentMessage)
  } else {
    // 移除Electron窗口状态监听器
    // 预加载未提供移除方法，这里依赖页面卸载即可
  }
})
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables.module.scss' as *;

.custom-title-bar {
  display: flex;
  align-items: center;
  width: 100%;
  top: 0;
  height: $custom-title-bar-height;
  background: linear-gradient(135deg, #4481eb 0%, #04befe 100%);
  color: white;
  user-select: none;
  -webkit-app-region: drag;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  position: fixed;
  z-index: 1000;
  .title-bar-left {
    display: flex;
    align-items: center;
    padding: 0 16px;
    min-width: 200px;
    -webkit-app-region: drag;

    .app-icon {
      width: 24px;
      height: 24px;
      margin-right: 8px;
      color: white;
    }

    .app-title {
      font-size: 14px;
      font-weight: 500;
      color: white;
      white-space: nowrap;
    }
  }

  .title-bar-nav {
    flex: 1;
    display: flex;
    justify-content: flex-start;
    // 导航区域默认可拖动
    -webkit-app-region: drag;

    // 导航菜单交互元素设置为 no-drag，确保点击不会触发拖动
    :deep(.el-menu .el-menu-item),
    :deep(.el-menu .el-sub-menu__title) {
      -webkit-app-region: no-drag;
    }

    // 弹出子菜单中的菜单项也应可点击，不触发拖动
    :deep(.el-sub-menu .el-menu--popup .el-menu-item) {
      -webkit-app-region: no-drag;
    }

    :deep(.el-menu) {
      background: transparent !important;
      border: none !important;
      align-items: center;
      padding: 0 12px;
      gap: 4px;

      .el-menu-item {
        color: rgba(255, 255, 255, 0.85) !important;
        background: rgba(255, 255, 255, 0.08) !important;
        border: 1px solid rgba(255, 255, 255, 0.12) !important;
        height: 76%;
        border-radius: 4px;
        padding: 0 20px;
        font-weight: 500;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        backdrop-filter: blur(10px);
        display: flex;
        align-items: center;
        margin: 0;

        &:hover {
          background: rgba(255, 255, 255, 0.15) !important;
          color: white !important;
          border-color: rgba(255, 255, 255, 0.25) !important;
          transform: translateY(-1px);
          box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
        }

        &.is-active {
          color: white !important;
          background: linear-gradient(135deg, rgba(255, 255, 255, 0.25) 0%, rgba(255, 255, 255, 0.15) 100%) !important;
          border: 1px solid rgba(255, 255, 255, 0.4) !important;
          box-shadow:
            0 4px 12px rgba(0, 0, 0, 0.2),
            inset 0 1px 2px rgba(255, 255, 255, 0.3);
          font-weight: 600;
        }
      }

      .el-sub-menu {
        .el-sub-menu__title {
          color: rgba(255, 255, 255, 0.85) !important;
          background: rgba(255, 255, 255, 0.08) !important;
          border: 1px solid rgba(255, 255, 255, 0.12) !important;
          border-radius: 10px;
          height: 76%;
          padding: 0 20px;
          font-weight: 500;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          backdrop-filter: blur(10px);
          display: flex;
          align-items: center;
          margin: 0;

          &:hover {
            background: rgba(255, 255, 255, 0.15) !important;
            color: white !important;
            border-color: rgba(255, 255, 255, 0.25) !important;
            transform: translateY(-1px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
          }
        }

        &.is-active .el-sub-menu__title {
          color: white !important;
          background: linear-gradient(135deg, rgba(255, 255, 255, 0.25) 0%, rgba(255, 255, 255, 0.15) 100%) !important;
          border: 1px solid rgba(255, 255, 255, 0.4) !important;
          box-shadow:
            0 4px 12px rgba(0, 0, 0, 0.2),
            inset 0 1px 2px rgba(255, 255, 255, 0.3);
          font-weight: 600;
        }
      }

      .el-sub-menu .el-menu--popup {
        background: rgba(255, 255, 255, 0.95) !important;
        backdrop-filter: blur(20px);
        border-radius: 12px;
        border: 1px solid rgba(255, 255, 255, 0.2);
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        padding: 8px 0;
        margin-top: 4px;

        .el-menu-item {
          color: #2c3e50 !important;
          background: transparent !important;
          border: none !important;
          border-radius: 6px;
          margin: 0 8px;
          padding: 0 12px;
          height: 40px;
          line-height: 40px;

          &:hover {
            background: rgba(64, 158, 255, 0.1) !important;
            color: #409eff !important;
            transform: none;
            box-shadow: none;
          }

          &.is-active {
            background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%) !important;
            color: white !important;
            font-weight: 600;
            box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
          }
        }
      }
    }
  }

  .title-bar-right {
    display: flex;
    align-items: center;
    -webkit-app-region: no-drag;

    .user-info {
      margin-right: 16px;

      .avatar-container {
        cursor: pointer;

        .avatar-wrapper {
          display: flex;
          align-items: center;
          padding: 8px 12px;
          border-radius: 6px;
          transition: background-color 0.3s;

          &:hover {
            background: rgba(255, 255, 255, 0.1);
          }

          .user-avatar {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            margin-right: 8px;
            border: 2px solid rgba(255, 255, 255, 0.3);
          }

          .user-nickname {
            font-size: 13px;
            color: white;
            font-weight: 500;
          }
        }
      }
    }

    .window-controls {
      display: flex;
      height: 100%;

      .control-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        // 响应式尺寸，适配不同标题栏高度
        width: clamp(26px, 3.2vh, 32px);
        height: clamp(26px, 3.2vh, 32px);
        margin-left: 12px;
        border: none;
        background: transparent;
        color: rgba(255, 255, 255, 0.8);
        border-radius: 50% 50%;
        cursor: pointer;
        transition: all 0.24s ease;
        -webkit-app-region: no-drag;

        // 默认图标尺寸
        svg {
          width: 12px;
          height: 12px;
        }
        // 现代化SVG图标样式，确保DPI清晰且切换平滑
        .icon {
          width: 16px;
          height: 16px;
          transition:
            opacity 0.24s ease,
            transform 0.24s ease;
        }
        &.close-btn {
          margin-right: 12px;
        }
        &:hover {
          background: rgba(255, 255, 255, 0.1);
          color: white;
        }

        &.close-btn:hover {
          background: #e74c3c;
          color: white;
        }
      }
    }
  }
}

// 图标切换过渡动画（200-300ms）
.icon-swap-enter-from,
.icon-swap-leave-to {
  opacity: 0;
  transform: scale(0.9);
}

.icon-swap-enter-active,
.icon-swap-leave-active {
  transition:
    opacity 0.24s ease,
    transform 0.24s ease;
}
</style>
